/**
 * Copyright (C) 2014  Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/
 *
 * This file is part of Dicoogle/dicoogle.
 *
 * Dicoogle/dicoogle is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Dicoogle/dicoogle is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Dicoogle.  If not, see <http://www.gnu.org/licenses/>.
 */
package pt.ua.dicoogle.rGUI.client.windows;

import java.awt.Image;
import java.awt.Toolkit;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.concurrent.Semaphore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import pt.ua.dicoogle.rGUI.client.AdminRefs;
import pt.ua.dicoogle.rGUI.interfaces.controllers.IPendingMessages;

/**
 *
 * @author Samuel Campos <samuelcampos@ua.pt>
 */
@Deprecated
public class FileAlreadyIndexed extends javax.swing.JFrame {

    private static IPendingMessages pendingMessages;

    private static Semaphore sem = new Semaphore(1, true);
    private static FileAlreadyIndexed instance;

    public static FileAlreadyIndexed getInstance() {
        try {
            sem.acquire();
            if (instance == null) {
                instance = new FileAlreadyIndexed();
            }
            sem.release();
        } catch (InterruptedException ex) {
            LoggerFactory.getLogger(FileAlreadyIndexed.class).error(ex.getMessage(), ex);
        }
        return instance;
    }

    /** Creates new form FileAlreadyIndexed */
    private FileAlreadyIndexed() {
        initComponents();

        this.setTitle("Re-Index Files");

        Image image = Toolkit.getDefaultToolkit().getImage(Thread.currentThread().getContextClassLoader().getResource("trayicon.gif"));
        this.setIconImage(image);

        jLabelNumber.setText("0");
        
        jListIndexedFiles.setModel(new DefaultListModel());

        pendingMessages = AdminRefs.getInstance().getPendingMessages();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListIndexedFiles = new javax.swing.JList();
        jButtonYes = new javax.swing.JButton();
        jButtonNo = new javax.swing.JButton();
        jCheckBoxApplyAll = new javax.swing.JCheckBox();
        jLabelNumber = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setText("The files listed bellow are already indexed:");

        jLabel2.setText("Do you want to index them again?");

        jScrollPane1.setViewportView(jListIndexedFiles);

        jButtonYes.setText("Yes");
        jButtonYes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonYesActionPerformed(evt);
            }
        });

        jButtonNo.setText("No");
        jButtonNo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNoActionPerformed(evt);
            }
        });

        jCheckBoxApplyAll.setText("apply to all");

        jLabelNumber.setText("#####");

        jLabel3.setText("Number of files:");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1)
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE)
                        .add(9, 9, 9))
                    .add(layout.createSequentialGroup()
                        .add(jCheckBoxApplyAll)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 138, Short.MAX_VALUE)
                        .add(jButtonYes)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButtonNo))
                    .add(jLabel2)
                    .add(layout.createSequentialGroup()
                        .add(jLabel3)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabelNumber)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel3)
                    .add(jLabelNumber))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jCheckBoxApplyAll)
                    .add(jButtonNo)
                    .add(jButtonYes))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNoActionPerformed
        DefaultListModel model = (DefaultListModel) jListIndexedFiles.getModel();

        if(jCheckBoxApplyAll.isSelected()){
             model.clear();
            
            jLabelNumber.setText("0");
            this.setVisible(false);
        }
        else{
            int[] indices = jListIndexedFiles.getSelectedIndices();

            if(indices.length > 0){

                for (int i = 0; i < indices.length; i++)
                    model.remove(indices[i]);

                //jListIndexedFiles.setModel(model);
                jLabelNumber.setText(String.valueOf(Integer.valueOf(jLabelNumber.getText()) - indices.length));

                if(model.isEmpty())
                    this.setVisible(false);
            }
            else
                JOptionPane.showMessageDialog(this, "You need to select some files.", "Select Files", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButtonNoActionPerformed

    private void jButtonYesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonYesActionPerformed
       boolean showTaskList = true;

        DefaultListModel model = (DefaultListModel) jListIndexedFiles.getModel();
        ArrayList<String> list = new ArrayList<String>();

        if(jCheckBoxApplyAll.isSelected()){
            Enumeration<String> en = (Enumeration<String>) model.elements();

            while(en.hasMoreElements())
                list.add(en.nextElement());

            if(list.size() > 0)
                AdminRefs.getInstance().reIndex(list);

            model.clear();
            
            jLabelNumber.setText("0");
            this.setVisible(false);
        }
        else{
            int[] indices = jListIndexedFiles.getSelectedIndices();

            if(indices.length > 0){

                for (int i = 0; i < indices.length; i++){
                    list.add((String) model.get(indices[i]));
                    model.remove(indices[i]);
                }

                AdminRefs.getInstance().reIndex(list);
                //jListIndexedFiles.setModel(model);
                jLabelNumber.setText(String.valueOf(Integer.valueOf(jLabelNumber.getText()) - indices.length));

                if(model.isEmpty())
                    this.setVisible(false);
            }
            else{
                JOptionPane.showMessageDialog(this, "You need to select some files.", "Select Files", JOptionPane.ERROR_MESSAGE);
                showTaskList = false;
            }
        }

        /*if (showTaskList)
        {
            TaskList tasks = TaskList.getInstance();
            tasks.setVisible(true);
            tasks.toFront();
        }*/
    }//GEN-LAST:event_jButtonYesActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        //if the user closes the window, none of the files will be reIndexed

        jCheckBoxApplyAll.setSelected(true);
        jButtonNo.doClick();
    }//GEN-LAST:event_formWindowClosing

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonNo;
    private javax.swing.JButton jButtonYes;
    private javax.swing.JCheckBox jCheckBoxApplyAll;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelNumber;
    private javax.swing.JList jListIndexedFiles;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables


    /**
     * Adds all the indexed files that can be re-indexed
     *
     * @param list of already indexed files
     */
    private synchronized void addAlreadyIndexedFiles(ArrayList<String> list){
        DefaultListModel model = (DefaultListModel) jListIndexedFiles.getModel();

        for(String filePath: list)
            model.addElement(filePath);

        //jListIndexedFiles.setModel(model);
        jListIndexedFiles.revalidate();
        this.repaint();
        jLabelNumber.setText(String.valueOf(Integer.valueOf(jLabelNumber.getText()) + list.size()));
    }

    /**
     * Get the list of already indexed files that can be re-indexed
     *
     * This list is accessible from the remote object PendingMessages, located on the server
     */
    public void getList(){
        try {
            ArrayList<String> list = pendingMessages.getFilesAlreadyIndexed();

            if(list != null && list.size() > 0){
                addAlreadyIndexedFiles(list);

                if (this.isVisible() == false)
                    this.setVisible(true);
            }

        } catch (RemoteException ex) {
            LoggerFactory.getLogger(FileAlreadyIndexed.class).error(ex.getMessage(), ex);
        }
    }
}
